package cn.b.sky.user.controller;

import cn.b.sky.common.enums.DwzCallbackType;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.common.utils.TreeUtil;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.ParameterService;
import cn.b.sky.user.service.model.ECode;
import cn.b.sky.user.service.model.ParameterEntity;
import cn.b.sky.user.service.model.ParameterFolder;
import cn.b.sky.user.service.model.ParameterValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;

/**
 * 
 * <strong>Title : ConfigController.java<br></strong>
 * <strong>Package : cn.b.sky.user.controller<br></strong>
 * <strong>Description : </strong>系统相关参数配置控制器<br> 
 * <strong>Create on : 2015-5-29 上午11:25:03<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@RequestMapping("/config/*")
@Controller
@Slf4j
public class ConfigController extends SecurityController {

  @Resource
  private ParameterService parameterService;

  @Resource
  private ECodeService eCodeService;

  /**
   * 
   * <strong>Title : commonCofig<br></strong>
   * <strong>Description : </strong>通用配置界面<br> 
   * <strong>Create on : 2015-5-29 下午1:13:44<br></strong>
   * <p>
   * @param model
   * @return
   * String
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping("commonConfig")
  public String commonCofig(Model model, String navTabId) {
    List<ParameterFolder> folders = parameterService.getAllParameterFolder(this.getSiteCode());
    List<ECode> valueTypeECode = eCodeService.selectECodeList(ECodeEnums.PARAMETER_VALUETYPECODE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute("parameterFolders",
        TreeUtil.gradingRecursion(folders.toArray(new ParameterFolder[folders.size()]), null));
    model.addAttribute("valueTypeECode", valueTypeECode);
    model.addAttribute(NAVTABID, navTabId);
    return "config/common_config";
  }

  @RequestMapping("geConfigDetail")
  @ResponseBody
  public DWZResult geConfigDetail(Model model, String parameterCode) {
    ParameterEntity parameter = parameterService.getParameterEntityByCode(parameterCode, this.getSiteCode());
    return ajaxDone(parameter);
  }

  @RequestMapping("getConfigCategory")
  @ResponseBody
  public DWZResult getConfigCategory(Model model, String folderCode) {
    ParameterFolder pf = parameterService.getParameterFolderByCode(folderCode, this.getSiteCode());
    return ajaxDone(pf);
  }

  @RequestMapping("saveConfigCategory")
  @ResponseBody
  public DWZResult saveConfigCategory(ParameterFolder folder, String navTabId, HttpServletRequest request, Model model) {
    if (folder == null || StringUtils.isBlank(folder.getFolderCode())) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "failedOp.M,directory.C,code.C,isNull.M"));
    }
    folder.setSiteCode(this.getSiteCode());
    setCreateInfo(folder);
    parameterService.saveParameterFolder(folder);
    String forwardUrl = getForwardUrl(request) + "/config/commonConfig?navTabId=" + navTabId;
    return navTabAjaxDone(navTabId, null, DwzCallbackType.FORWARD, forwardUrl, null, null);
  }

  @RequestMapping("modifyConfigCategory")
  @ResponseBody
  public DWZResult modifyConfigCategory(ParameterFolder folder, String navTabId, HttpServletRequest request, Model model) {
    if (folder == null || StringUtils.isBlank(folder.getFolderCode())) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "failedOp.M,directory.C,code.C,isNull.M"));
    }
    folder.setSiteCode(this.getSiteCode());
    setCreateInfo(folder);
    parameterService.modifyParameterFolder(folder);
    String forwardUrl = getForwardUrl(request) + "/config/commonConfig?navTabId=" + navTabId;
    return navTabAjaxDone(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "successfulOperation.M"),
        navTabId, null, DwzCallbackType.FORWARD, forwardUrl, null, null);
  }

  @RequestMapping("saveConfig")
  @ResponseBody
  public DWZResult saveConfig(ParameterEntity parameter, String navTabId, HttpServletRequest request, Model model) {
    if (parameter == null || StringUtils.isBlank(parameter.getParameterCode())) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "failedOp.M,project.C,code.C,isNull.M"));
    }
    if (checkRepeatEnum(parameter.getParameterValue())) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "failedOp.M,enumValueCanNotRepeat.C"));
    }
    try {
      parameter.setSiteCode(this.getSiteCode());
      setCreateInfo(parameter);
      parameterService.saveSyParameter(parameter);
      String forwardUrl = getForwardUrl(request) + "/config/commonConfig?navTabId=" + navTabId;
      return navTabAjaxDone(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "successfulOperation.M"),
          navTabId, null, DwzCallbackType.FORWARD, forwardUrl, null, null);
    } catch (Exception e) {
      log.error("{}", e);
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "failedOperation.M"));

    }

  }

  /**
   * 
   * <strong>Title : checkRepeatEnum<br></strong>
   * <strong>Description : </strong>判断是否有重复，重复返回true，不重复就false<br> 
   * <strong>Create on : 2016-11-7 下午1:31:54<br></strong>
   * <p>
   * @param parameterValue
   * @return
   * Boolean
   * @throws 
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  private Boolean checkRepeatEnum(List<ParameterValue> parameterValue) {
    if (parameterValue != null && parameterValue.size() > 1) {
      return parameterValue.size() != new HashSet<ParameterValue>(parameterValue).size();
    }
    return false;
  }

  @RequestMapping("modifyConfig")
  @ResponseBody
  public DWZResult modifyConfig(ParameterEntity parameter, String navTabId, HttpServletRequest request, Model model) {
    if (parameter == null || StringUtils.isBlank(parameter.getParameterCode())) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "failedOp.M,project.C,code.C,isNull.M"));
    }
    if (checkRepeatEnum(parameter.getParameterValue())) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "failedOp.M,enumValueCanNotRepeat.C"));
    }
    try {
      parameter.setSiteCode(this.getSiteCode());
      setCreateInfo(parameter);
      parameterService.modifySyParameter(parameter);
      String forwardUrl = getForwardUrl(request) + "/config/commonConfig?navTabId=" + navTabId;
      return navTabAjaxDone(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "successfulOperation.M"),
          navTabId, null, DwzCallbackType.FORWARD, forwardUrl, null, null);
    } catch (Exception e) {
      log.error("{}", e);
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), "failedOperation.M"));

    }

  }

  @RequestMapping("deleteConfigCategory")
  @ResponseBody
  public DWZResult deleteConfigCategory(Model model, String folderCode) {
    if (StringUtils.isBlank(folderCode)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "failedOp.M,directory.C,code.C,isNull.M"));
    }
    parameterService.deleteConfigCategory(folderCode, this.getSiteCode());
    return ajaxDone(null); //操作成功，给出提示。
  }

  @RequestMapping("deleteConfig")
  @ResponseBody
  public DWZResult deleteConfig(Model model, String parameterCode) {
    if (StringUtils.isBlank(parameterCode)) {
      return ajaxError(getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(),
          "failedOp.M,project.C,code.C,isNull.M"));
    }
    parameterService.deleteConfig(parameterCode, this.getSiteCode());
    return ajaxDone(null); //操作成功，给出提示。
  }

  @RequestMapping("isExitsConfigCategory")
  @ResponseBody
  public boolean isExitsConfigCategory(String folderCode, Model model) {
    if (!StringUtils.isBlank(folderCode)) {
      ParameterFolder pf = parameterService.getParameterFolderByCode(folderCode, this.getSiteCode());
      if (pf != null && !StringUtils.isBlank(pf.getFolderCode())) {
        return false;
      }
    }
    return true;
  }

  @RequestMapping("isExitsConfig")
  @ResponseBody
  public boolean isExitsConfig(String parameterCode, Model model) {
    if (!StringUtils.isBlank(parameterCode)) {
      try {
        ParameterEntity pf = parameterService.getParameterEntityByCode(parameterCode, this.getSiteCode());
        if (pf != null && !StringUtils.isBlank(pf.getParameterCode())) {
          return false;
        }
      } catch (ImeException e) {
        log.error("{}", e);
        if ("systemParameterIsnotDefine.M".equals(e.getErrorCode())) {
          return true;
        }
      }

    }
    return true;
  }

  @RequestMapping("getParameterValue")
  public String getParameterValue(String parameterCode, Model model) {
    List<ParameterValue> pvs = parameterService.getParameterValuesByPCode(parameterCode, this.getSiteCode());
    model.addAttribute("parameterCode", parameterCode);
    model.addAttribute("parameterValues", pvs);
    return "config/enum_list";
  }

  @RequestMapping("testSqlData")
  public String testSqlData(String sql, Model model) {
    try {
      List<ParameterValue> pvs = parameterService.getParameterValueBySql(sql);
      model.addAttribute("parameterValues", pvs);
    } catch (ImeException e) {
      log.error("{}", e);
      model.addAttribute("message", e.getMessage());
    }
    return "config/dynic_sqldata";
  }
}
